import { useSelector, useDispatch } from "react-redux";
import { useCallback } from "react";
import ShoppingCartAPi from "../api/shoppingCart";
import UsersApi from "../api/users";
import Creators from "../store/actions";



export const useAddShoppingCart = () => {
  const dispatch = useDispatch();
  const addShoppingCart = useSelector(state => state.add_shoppingCart);

  // 得到用户id和秒杀id发送请求获取完整数据
  const getAddCartData = useCallback(async (seckill_id) => {
    const user_id = UsersApi.getUserId();
    const data = await ShoppingCartAPi.getAddCartData({ user_id, seckill_id })
    console.log(data);
    dispatch(Creators.getAddCartData(data));
  }, [dispatch])

  // 数字输入框变化函数
  const changeCount = useCallback((count) => {
    dispatch(Creators.getAddCartData({ count }));
  }, [dispatch])

  // 新增购物车商品
  const addComm = async () => {
    const { user, seckill, count } = addShoppingCart;
    const user_id = user._id;
    const seckill_id = seckill._id;
    return await ShoppingCartAPi.addComm({ user_id, seckill_id, count });
  };

  return [addShoppingCart, { getAddCartData, changeCount, addComm }];

}